package org.wesc.boot.webapi.api.system;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.wesc.boot.common.annotation.ApiEndpoint;
import org.wesc.boot.common.api.R;
import org.wesc.boot.dao.domain.QueryRequest;
import org.wesc.boot.dao.entity.Role;
import org.wesc.boot.dao.entity.RoleMenu;
import org.wesc.boot.dao.model.RoleQueryModel;
import org.wesc.boot.dao.model.RoleResultModel;
import org.wesc.boot.service.system.menu.MenuAdvanceService;
import org.wesc.boot.service.system.role.RoleAdvanceService;
import org.wesc.boot.webapi.base.BaseApi;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Wesley
 */
@Api(tags = {"角色接口"})
@Slf4j
@Validated
@RestController
@RequestMapping("/api/role")
public class RoleApi extends BaseApi {

    private final RoleAdvanceService roleAdvanceService;

    private final MenuAdvanceService menuAdvanceService;

    @Autowired
    public RoleApi(RoleAdvanceService roleAdvanceService, MenuAdvanceService menuAdvanceService) {
        this.roleAdvanceService = roleAdvanceService;
        this.menuAdvanceService = menuAdvanceService;
    }

    @ApiOperation(value = "查看角色")
    @GetMapping
    @RequiresPermissions("role:view")
    public R<Map<String, Object>> roleList(QueryRequest queryRequest, RoleQueryModel roleQueryModel) {
        return R.data(getDataTable(roleAdvanceService.findRoles(roleQueryModel, queryRequest)));
    }

    @ApiOperation(value = "校验角色名称")
    @GetMapping("check/{roleName}")
    public R<Boolean> checkRoleName(@NotBlank(message = "{required}") @PathVariable String roleName) {
        Role result = this.roleAdvanceService.findByName(roleName);
        return R.data(null == result);
    }

    @ApiOperation(value = "获取角色菜单")
    @GetMapping("menu/{roleId}")
    public R<List<String>> getRoleMenus(@NotBlank(message = "{required}") @PathVariable String roleId) {
        List<RoleMenu> list = this.menuAdvanceService.findMenuByRoleId(Long.parseLong(roleId));
        return R.data(list.stream().map(roleMenu -> String.valueOf(roleMenu.getMenuId())).collect(Collectors.toList()));
    }

    @ApiOperation(value = "新增角色")
    @PostMapping
    @RequiresPermissions("role:add")
    @ApiEndpoint(operation = "新增角色", exception = "新增角色失败")
    public R<String> addRole(@Valid RoleResultModel roleResultModel) {
        try {
            this.roleAdvanceService.createRole(roleResultModel);
            return R.success();
        } catch (Exception e) {
            String message = "新增角色失败";
            log.error(message, e);
            return R.fail(message);
        }
    }

    @ApiOperation(value = "删除角色")
    @DeleteMapping("/{roleIds}")
    @RequiresPermissions("role:delete")
    @ApiEndpoint(operation = "删除角色", exception = "删除角色失败")
    public R<String> deleteRoles(@NotBlank(message = "{required}") @PathVariable String roleIds) {
        try {
            String[] ids = roleIds.split(StringPool.COMMA);
            this.roleAdvanceService.deleteRoles(ids);
            return R.success();
        } catch (Exception e) {
            String message = "删除角色失败";
            log.error(message, e);
            return R.fail(message);
        }
    }

    @ApiOperation(value = "修改角色")
    @PutMapping
    @RequiresPermissions("role:update")
    @ApiEndpoint(operation = "修改角色", exception = "修改角色失败")
    public R<String> updateRole(@Valid RoleResultModel roleResultModel) {
        try {
            this.roleAdvanceService.updateRole(roleResultModel);
            return R.success();
        } catch (Exception e) {
            String message = "修改角色失败";
            log.error(message, e);
            return R.fail(message);
        }
    }

    @ApiOperation(value = "导出角色")
    @PostMapping("excel/export")
    @RequiresPermissions("role:export")
    @ApiEndpoint(operation = "导出角色", exception = "导出角色失败")
    public void exportExcel(QueryRequest queryRequest, RoleQueryModel model, HttpServletResponse response) throws IOException {
        response.setContentType("APPLICATION/OCTET-STREAM;charset=UTF-8");
        String sheetName = "角色列表";
        List<Role> roleList = this.roleAdvanceService.findRoles(model, queryRequest).getRecords();
        EasyExcel.write(response.getOutputStream(), Role.class).sheet(sheetName).doWrite(roleList);
    }
}
